import { FormUpload } from '@components/FormUpload'
import { useFormCallback } from '@hooks/useFormCallback'
import { useProductCreateMutation, useProductUpdateMutation } from '@services/product'
import { Link } from '@tanstack/react-router'
import {
  Breadcrumb,
  Button,
  DatePicker,
  Form,
  Input,
  InputNumber,
  Space,
  Switch,
  Tabs,
} from 'antd'
import dayjs from 'dayjs'
import { useEffect, useState } from 'react'
import { FormCard } from './FormCard'
import ImagePreview from './ImagePreview'

const tabs = {
  basic: {
    key: 'basic',
    label: '基本信息',
    requiredFields: ['serial_no', 'title', 'product_category_id', 'image'],
    rules: {
      serial_no: [{ required: true, message: '请输入商品编号' }],
      title: [
        { required: true, message: '请输入商品名称' },
        { min: 5, message: '商品名称长度不能小于5' },
        { max: 50, message: '商品名称长度不能大于50' },
      ],
      product_category_id: [{ required: true, message: '请选择商品分类' }],
      image: [{ required: true, message: '请上传商品图片' }],
    },
  },
  priceStock: {
    key: 'priceStock',
    label: '价格库存',
    requiredFields: ['price', 'unit', 'stock'],
    rules: {
      price: [{ required: true, message: '请输入商品价格' }],
      unit: [{ required: true, message: '请输入商品单位' }],
      stock: [{ required: true, message: '请输入商品库存' }],
    },
  },
  info: {
    key: 'info',
    label: '产品内容',
    requiredFields: ['description', 'content'],
    rules: {
      description: [{ required: true, message: '请输入产品描述' }],
      content: [{ required: true, message: '请输入产品内容' }],
    },
  },
}

export default function FormProduct({ defaultData }) {
  console.log('%c Line:59 🌭 defaultData', 'color:#4fff4B', defaultData)
  const [data, setData] = useState(defaultData)

  const [form] = Form.useForm()
  const [position] = useState('left')
  const [activeTab, setActiveTab] = useState(tabs.basic.key)

  const [images, setImages] = useState(defaultData?.images || []) // 图片集
  const [attachments, setAttachments] = useState(defaultData.items || []) // 附件

  const { mutate } = defaultData.id ? useProductUpdateMutation() : useProductCreateMutation()
  const { onFinish, onFailed } = useFormCallback(mutate, {
    handle: (values) => {
      const newValues = {
        ...values,
        ...(defaultData.id && { id: defaultData.id }),
        images,
        items: attachments,
        published_at: dayjs(values.published_at).format('YYYY-MM-DD'),
      }
      return newValues
    },
  })

  useEffect(() => {
    form.setFieldsValue({ ...defaultData, published_at: dayjs(defaultData.published_at) })
  }, [])

  const next = () => {
    if (activeTab === tabs.basic.key) {
      form
        .validateFields(tabs.basic.requiredFields)
        .then(() => setActiveTab(tabs.priceStock.key))
        .catch(onFailed)
    } else if (activeTab === tabs.priceStock.key) {
      form
        .validateFields(tabs.priceStock.requiredFields)
        .then(() => setActiveTab(tabs.info.key))
        .catch(onFailed)
    }
  }

  const prev = () => {
    if (activeTab === tabs.priceStock.key) {
      setActiveTab(tabs.basic.key)
    } else if (activeTab === tabs.info.key) {
      setActiveTab(tabs.priceStock.key)
    }
  }

  const createSerialNo = (form) => {
    const newSerialNo = `SN${Math.random().toString().slice(2, 10)}`
    // 同时更新状态和表单字段值
    setData((prev) => ({ ...prev, serial_no: newSerialNo }))
    form.setFieldsValue({ serial_no: newSerialNo })
  }

  // 设置封面逻辑
  const handleImage = (e, file) => {
    e.preventDefault()
    console.log('%c Line:117 🍿 file', 'color:#3f7cff', e, file)
    if (file?.url) {
      setData((prev) => ({ ...prev, image: file.url }))
      form.setFieldsValue({ image: file.url })
    }
  }

  const tabItems = [
    {
      ...tabs.basic,
      forceRender: true,
      children: (
        <>
          <Form.Item label="商品编号" name="serial_no" rules={tabs.basic.rules.serial_no}>
            <Space.Compact style={{ width: '100%' }}>
              {/* 使用 serialNo 状态值作为 Input 的 value */}
              <Input
                className="w-[206px]!"
                value={data.serial_no}
                onChange={(e) => setData((prev) => ({ ...prev, serial_no: e.target.value }))}
              />
              <Button type="primary" onClick={() => createSerialNo(form)}>
                生成
              </Button>
            </Space.Compact>
          </Form.Item>
          <Form.Item label="商品名称" name="title" rules={tabs.basic.rules.title}>
            <Input min={5} max={50} />
          </Form.Item>
          <Form.Item
            label="商品分类"
            name="product_category_id"
            rules={tabs.basic.rules.product_category_id}>
            <Input />
          </Form.Item>
          <Form.Item label="商品封面" name="image" rules={tabs.basic.rules.image}>
            <ImagePreview
              key="image"
              aspect="9:4"
              url={data.image}
              onChange={(resp) => {
                setData((prev) => ({ ...prev, image: resp.url }))
                form.setFieldValue('image', resp.url)
              }}
            />
          </Form.Item>
          <Form.Item label="产品图片" name="images" width={'206px'}>
            <FormUpload
              key="images"
              filelist={images}
              btnText="上传图片"
              onChange={setImages}
              extra={
                <Button checkUrl={data.image} variant="link" color="default" onClick={handleImage}>
                  设置封面
                </Button>
              }
            />
          </Form.Item>
          <Form.Item label="排　　序" name="orderby" width={'206px'}>
            <InputNumber className="w-[206px]!" min={0} />
          </Form.Item>

          <Form.Item label="是否推荐" name="is_recommend">
            <Switch checkedChildren="推荐" unCheckedChildren="不推荐" />
          </Form.Item>
          <Form.Item label="是否显示" name="is_show">
            <Switch checkedChildren="显示" unCheckedChildren="隐藏" />
          </Form.Item>
          <div className="flex justify-end">
            <Button type="primary" onClick={next}>
              下一步
            </Button>
            {defaultData.id && (
              <Button type="primary" htmlType="submit" className="ml-2">
                保存
              </Button>
            )}
          </div>
        </>
      ),
    },
    {
      ...tabs.priceStock,
      forceRender: true,
      children: (
        <>
          <Form.Item
            label="商品价格"
            name="price"
            width={'206px'}
            rules={[{ required: true, message: '请输入商品价格' }]}>
            <InputNumber className="w-[206px]!" min={0} />
          </Form.Item>
          <Form.Item
            label="商品单位"
            width={'206px'}
            name="unit"
            rules={[{ required: true, message: '请输入商品单位' }]}>
            <Input className="w-[206px]!" />
          </Form.Item>
          <Form.Item
            label="商品库存"
            width={'206px'}
            name="stock"
            rules={[{ required: true, message: '请输入商品库存' }]}>
            <InputNumber className="w-[206px]!" />
          </Form.Item>
          <div className="flex justify-end gap-2">
            <Button onClick={prev}>上一步</Button>
            <Button type="primary" onClick={next}>
              下一步
            </Button>
            {defaultData.id && (
              <Button type="primary" htmlType="submit" className="ml-2">
                保存
              </Button>
            )}
          </div>
        </>
      ),
    },
    {
      ...tabs.info,
      forceRender: true,
      children: (
        <>
          <Form.Item
            label="商品描述"
            name="description"
            rules={[{ required: true, message: '请输入商品描述' }]}>
            <Input.TextArea rows={3} />
          </Form.Item>
          <Form.Item
            className="w-full"
            label="商品内容"
            name="content"
            rules={[{ required: true, message: '请输入商品内容' }]}>
            <Input.TextArea rows={5} />
          </Form.Item>

          <Form.Item label="产品附件" name="items" width={'206px'}>
            <FormUpload
              key="items"
              filelist={attachments}
              btnText="上传附件"
              onChange={setAttachments}
            />
          </Form.Item>
          <Form.Item label="发布时间" name="published_at">
            <DatePicker className="w-[206px]!" />
          </Form.Item>
          <div className="flex justify-end gap-2">
            <Button onClick={prev}>上一步</Button>
            <Button type="primary" htmlType="submit">
              保存
            </Button>
          </div>
        </>
      ),
    },
  ]

  const card = {
    title: (
      <Breadcrumb
        items={[
          { title: '产品中心' },
          { title: <Link to="..">产品管理</Link> },
          { title: defaultData?.id ? '编辑' : '新增' },
        ]}
      />
    ),
  }

  return (
    <FormCard card={card}>
      <Form
        name="product"
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 18 }}
        style={{ maxWidth: '100%' }}
        form={form}
        onFinish={onFinish}
        onFinishFailed={onFailed}
        autoComplete="off">
        <Tabs
          tabPosition={position}
          activeKey={activeTab}
          onChange={setActiveTab}
          items={tabItems}
        />
      </Form>
    </FormCard>
  )
}
